<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use App\Socialite as SocialModel;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class OauthController extends Controller
{

    use AuthenticatesUsers;

    public function redirectToProvider($driver)
    {
        return Socialite::driver($driver)->redirect();
    }

    public function handleProviderCallback(Request $request, $driver)
    {
        $user = Socialite::driver($driver)->user();
        $socialite = $this->getSocialiteUser($user, $driver);

        if ($auth = $socialite->user) {
            Auth::login($auth);
            return $this->sendLoginResponse($request);
        } else {
            session(['socialite' => $socialite]);
            session(['oauth_user' => $user]);
            $redirectUrl = session('redirect_url', route('user.index'));
            return redirect($redirectUrl);
        }
    }

    private function getSocialiteUser($user, $driver = 'wechat')
    {
        $where = [
            ['slug', $user->openid],
            ['driver', $driver]
        ];

        $socialite = SocialModel::where($where)->firstOrCreate([
            'slug' => $user->openid,
            'driver' => $driver
        ]);

        return $socialite;
    }
}
